<template>
  <div>
    <ltext :width="width" :model-value="modelValue" :disabled="disabled" :readonly="true" @click="open" :height="height"  />
    <el-dialog v-model="show" destroy-on-close>
      <div style="display: flex;">
        <div :class="['item', ids.indexOf(item.id)!==-1 ?'active':'']" v-for="(item, index) in list" :key="index" @click="select(item)">
          {{item.name}}
        </div>
      </div>
      <div style="margin-top: 20px;">
        <lbtn  size="large" @click="confirm">确定</lbtn >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import tool from "@/utils/tool";

export default {
  name: 'deliver',
  props: {
    width: {type: [String, Number], default: 150},
    height: { type: [Number, String], default: '' },
    modelValue: {
      type: String, default: ''
    },
    disabled: {
      type: Boolean, default: false
    },
  },
  emits: ['update:modelValue', 'update:ids', 'change'],
  data () {
    return {
      show: false,
      list: [],
      texts: [],
      ids: []
    }
  },
  methods: {
    open () {
      if(!this.disabled) {
        this.show = true
        tool.post('common/dropdown', {cat: 'deliverList'}).then(ret => {
          this.list = ret.data
          if(this.modelValue) {
            this.texts = []
            this.ids = []
            let model = this.modelValue.split(',')
            this.list.map(row => {
              if(model.indexOf(row.name) !== -1) {
                this.texts.push(row.name)
                this.ids.push(row.id)
              }
            })
          }
        })
      }
    },
    select (item) {
      if(this.ids.indexOf(item.id) === -1) {
        this.ids.push(item.id)
      }
      else {
        this.ids.splice(this.ids.indexOf(item.id), 1)
      }
      if(this.texts.indexOf(item.name) === -1) {
        this.texts.push(item.name)
      }
      else {
        this.texts.splice(this.texts.indexOf(item.name), 1)
      }
    },
    confirm () {
      this.$emit('update:ids', this.ids.join(','))
      this.$emit('update:modelValue', this.texts.join(','))
      this.$emit('change', this.ids.join(','))
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  border: 1px solid #2b85e4;
  width: 120px;
  margin: 5px;
  padding: 5px 0;
  user-select: none;
  &:hover {
    cursor: pointer;
  }
  &.active {
    background-color: #2b85e4;
    color: white;
  }
}
</style>